package com.maventools.utils;

import com.maventools.config.DownloadConfig;
import com.maventools.domain.Maven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: maventools
 * @BelongsPackage: com.maventools.config
 * @Author: Layila
 * @CreateTime: 2025-04-20  10:40
 * @Description: 下载配置maven工具类
 * @Version: 1.0
 * @Since:Java17
 */
@Component
public class InstallMavenUtils {
    @Autowired
    private DownloadConfig downloadConfig;
    @Autowired
    private FilesUtils fu;
    @Autowired
    private EnvUtils eu;

    public List<Maven> getMavenList() throws Exception {
        List<String> mavenVersionList = this.fetchMavenVersionsFromMavenCentral();
        List<Maven> mavenList = new ArrayList<>();
        for (String version : mavenVersionList) {
            Maven maven = new Maven();
            maven.setVersion(version);
            mavenList.add(maven);
        }

        return mavenList; // Return the populated list
    }

    /*
     * @Description:  解析中央仓库的xml文件获取maven版本
     * @param
     * @return: List<String>
     * @Author:  Layla
     * @date:  2025/4/20 9:46
     */
    public List<String> fetchMavenVersionsFromMavenCentral() throws Exception {
        List<String> versions = new ArrayList<>();

        URL url = new URL(downloadConfig.getMetadataUrl());
        InputStream inputStream = url.openStream();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputStream);
        doc.getDocumentElement().normalize();
        NodeList versionNodes = doc.getElementsByTagName("version");
        for (int i = 0; i < versionNodes.getLength(); i++) {
            Element versionElement = (Element) versionNodes.item(i);
            versions.add(versionElement.getTextContent());
        }
        return versions;
    }

    /**
     * @Descrption 下载工具主方法
     * @param version
     * @param type
     * @return
     */
    public boolean Installer(String version, boolean type) {
        String downloadUrl = fu.generateDownloadUrl(downloadConfig.getDownloadUrl(), version, type);
        //构造文件名称
        String fileName = "apache-maven-" + version + (type ? "-bin.zip" : "-src.zip");
        // 构造完整的文件路径
        String targetDirectory = downloadConfig.getTargetURL();
        Path targetPath = Paths.get(targetDirectory, fileName); // Use targetDirectory
        Path directoryPath = Paths.get(targetDirectory);
        System.out.println("下载地址" + downloadUrl);
        System.out.println("解压目的地址" + targetDirectory);
        System.out.println("下载本地地址/解压目标地址" + targetPath);
        if (!Files.exists(directoryPath)) {
            try {
                Files.createDirectories(directoryPath);
            } catch (IOException e) {
                System.err.println("Failed to create directory: " + directoryPath);
                throw new RuntimeException("Failed to create directory", e);
            }
        }
        try {
            fu.downloadFile(downloadUrl, targetPath); // 下载
            fu.unzip(targetPath.toString(), targetDirectory); //解压
            eu.setEnvPath(downloadConfig.getTargetURL()+"/apache-maven-"+version); //设置环境变量
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
